﻿using voidbox;
using System;
using System.Collections.Generic;
using System.Text;
using TTEngine.Graphics;
using TTEngine.Resource;
using TTEngine.TTMath;

namespace TTEngine.Framework.UI
{
    //UITarget 是把部分UI绘制到一个RenderTarget上，然后作为一个UI的子UI
    public class UITarget : UIBaseElement
    {
        public ITarget Target
        {
            get;
            private set;
        }
        public RenderTarget RenderTarget
        {
            get
            {
                return Target as RenderTarget;
            }
            set
            {
                Target = value;                
            }
        }
        public bool IsRenderTarget
        {
            get
            {
                return Target is IRenderTarget;
            }
        }
       
        public UICanvas Canvas
        {
            get;
            private set;
        }
        public CommonResource Resource
        {
            get;
            private set;
        }
        public UITarget(ITarget target, CommonResource resource)
        {
            this.Target = target;
            Resource = resource;
            Canvas = new UICanvas(target, resource);
        }

        public void SetSize(uint width, uint height)
        {
            if (RenderTarget != null)
            {
                RenderTarget.TryDecRefAndDestory();
            }
            RenderTarget = new RenderTarget(Resource.Package, width, height, TextureType.RGBA_32);
            this.Canvas.SetTarget(RenderTarget);
        }
        public void TargetUpdate(float delta)
        {
            Canvas.OnUpdate(null, delta);
        }
        public Color clearColor;
        public void TargetRender()
        {
            Target.Apply();
            Target.RenderInfo.RecordFrame_Begin();
            Target.Clear(clearColor);

            Canvas.OnRender(null);
            Target.RenderInfo.RecordFrame_End();
        }

        public override void OnUpdate(UICanvas canvas, float delta)
        {
            TargetUpdate(delta);
        }
        public override void OnRender(UICanvas canvas)
        {
            if (!IsRenderTarget)
                throw new Exception("Only RenderTarget UITarget can use as a child.");
            TargetRender();

            //恢复Canvas绘制状态
            canvas.Target.Apply();
            canvas._camera.Apply();

            var dest = this.GetWorldRect();

            canvas.Batcher.EndDraw();
            //canvas.Batcher.ZTest = true;
            //canvas.Batcher.ZWrite = true;

            canvas.Batcher.GetSingleTextureBatcher().Draw(this.Target as IRenderTarget, fAABB.One, dest, 0, Color32.White);

            //canvas.Batcher.ZTest = false;
            //canvas.Batcher.ZWrite = false;
            canvas.Batcher.EndDraw();
            base.OnRender(canvas);
        }
    }
}
